package edu.gatech.gro.model.parser;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;
import edu.gatech.gro.model.Item;

public class ItemJsonHandler extends JsonHandler {

	private static final String TAG = "ITEM_TYPE_JSON_HANDLER";

	@Override
	protected void parseDataArray() {
		List<Item> dataParsed = new ArrayList<Item>();
		try {
			JSONArray array = json.getJSONArray("data");
			for (int i = 0; i < array.length(); i++) {
				dataParsed.add(getItem(array.getJSONObject(i)));
			}
		} catch (JSONException e) {
			Log.e(TAG, e.getMessage());
		}
		getResponse().setData(dataParsed);
	}

	@Override
	protected void parseData() {
		Item dataParsed = null;
		try {
			dataParsed = getItem(json.getJSONObject("data"));
		} catch (JSONException e) {
			Log.e(TAG, e.getMessage());
		}
		getResponse().setData(dataParsed);
	}

	public Item getItem(JSONObject obj) {
		Item i = new Item();
		try {
			parseAbstractObject(i, obj);
			i.setName(obj.getString("name"));
			i.setItemTypeId(obj.getInt("itemTypeId"));
			i.setGroceryStoreId(obj.getInt("groceryStoreId"));
			i.setBarCode(obj.getString("barCode"));
			i.setPrice(obj.getDouble("price"));
			i.setCurrency(obj.getInt("currency"));
		} catch (JSONException e) {
			Log.e(TAG, e.getMessage());
		}
		return i;
	}
}
